<template>
  <div class="box-padding">
    <div class="page-container">
      <div class="left-panel">
        <el-descriptions class="margin-top" :column="3" border>
          <el-descriptions-item label="断面名称">
            {{ formData.dmmc }}
          </el-descriptions-item>
          <el-descriptions-item label="旗区名称">
            {{ formData.xzqhname }}
          </el-descriptions-item>
          <el-descriptions-item label="监测日期">
            <el-date-picker v-model="formData.jcsj" type="date" placeholder="选择日期" :clearable="false"
              :picker-options="pickerOptions()" @change="handdatepicker">
            </el-date-picker>
          </el-descriptions-item>
          <el-descriptions-item label="水质监测">
            <el-upload class="upload-demo" :before-upload="handleChange" :show-file-list="false"
              style="display:inline-block;" action="" :limit="1">
              <el-button size="small" type="primary">模板上传</el-button>
            </el-upload>
            <el-button style="margin-left: 10px;" type="primary" size="small"
              @click="handxiazai('生态补奖项目模板.xlsx')">模板下载</el-button>
          </el-descriptions-item>
          <el-descriptions-item label="其他情况" :span="2">
            <el-radio-group v-model="formData.jianceshujulx">
              <el-radio label="01">正常</el-radio>
              <el-radio label="03">合理断流</el-radio>
              <el-radio label="05">不合理断流</el-radio>
            </el-radio-group>
          </el-descriptions-item>
          <el-descriptions-item label="监测报告上传" :span="3">
            <el-upload class="upload-demo" :action="uploadUrl" :data="{ fileType: '' }"
              :on-success="handleUploadSuccess" :on-remove="handleRemove" :on-error="handerror" :file-list="fileList"
              multiple>
              <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="right-panel">
        <!-- 左侧表格 -->
        <div class="table-container">
          <el-table :data="splitTableData(1)" style="width: 100%; height: 100%">
            <el-table-column prop="name" label="监测因子"></el-table-column>
            <el-table-column prop="cdz" label="测定值">
              <template slot-scope="scope">
                <el-input v-model="formData[scope.row.jcxm]" @input="calculateCategory(scope.row)">
                  <span slot="suffix" class="custom-suffix">{{
                    scope.row.units
                    }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="lb" label="类别">
              <template slot-scope="scope">
                {{
                  scope.row.lb
                    ? config.typeArray.find(
                      (item) => item.value == scope.row.lb
                    ).label
                    : ""
                }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 右侧表格 -->
        <div class="table-container">
          <el-table :data="splitTableData(2)" style="width: 100%; height: 100%">
            <el-table-column prop="name" label="监测因子"></el-table-column>
            <el-table-column prop="cdz" label="测定值">
              <template slot-scope="scope">
                <el-input v-model="formData[scope.row.jcxm]" @input="calculateCategory(scope.row)">
                  <span slot="suffix" class="custom-suffix">{{
                    scope.row.units
                    }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="lb" label="类别">
              <template slot-scope="scope">
                {{
                  scope.row.lb
                    ? config.typeArray.find(
                      (item) => item.value == scope.row.lb
                    ).label
                    : ""
                }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="bottom-actions">
      <el-button @click="goBack" size="medium">返回</el-button>
      <el-button type="primary" @click="submitForm('100')" size="medium">保存</el-button>
      <el-button type="success" @click="submitForm('101')" size="medium">提交</el-button>
      <!-- <el-button @click="resetForm('formData')">重置</el-button> -->
    </div>
  </div>
</template>

<script>
import config from "@/config/config";
import * as XLSX from "xlsx";
import moment from 'moment'

export default {
  data() {
    return {
      config,
      uploadUrl: "",
      isEditable: true, // 是否可编辑旗区名称
      isViewPage: false, // 是否为查看页面，默认为否
      fileList: [],

      formData: {
        id: null,
        szlb: null,
        jcsj: null,
        xzqhdm: null,
        dmmc: null,
        sw: null,
        // swfl: null,
        ph: null,
        // phfl: null,
        rjy: null,
        gmsyzs: null,
        cod: null,
        bod5: null,
        nh3n: null,
        zl: null,
        zd: null,
        tong: null,
        xin: null,
        meng: null,
        fhw: null,
        xi: null,
        shen: null,
        gong: null,
        ge: null,
        luo: null,
        qian: null,
        qhw: null,
        hff: null,
        syl: null,
        ylzbmhxj: null,
        lhw: null,
        fdcjq: null,
        zl1: null,
        shenhezt: null,
        filename: null,
        url: null,
        jianceshujulx: null,
        createtime: new Date(),
        updatetime: null,
        jianceshujulx: '01',
      },
      leftTableData: [],
      rightTableData: [],
      tableData: [],
    };
  },
  mounted() {
    // this.splitTableData();
    console.log(this.$route);
    console.log(moment().endOf('month').format('YYYY-MM-DD'));
  },
  created() {
    this.uploadUrl =
      process.env.VUE_APP_BASE_URL + "/rest/uploadMultipleFileNew";
    // this.fetchData();
    if (!this.$route.params.openType) {
      this.goBack();
      return;
    }
    let newArray = [];
    config.jcjgArray.forEach((element) => {
      if (element.value != "zl1") {
        newArray.push({
          name: element.label,
          jcxm: element.value,
          cdz: "",
          lb: "",
          lb1: element.lb1,
          lb2: element.lb2,
          lb3: element.lb3,
          lb4: element.lb4,
          lb5: element.lb5,
          fh: element.fh,
          units: element.units,
        });
      }
    });
    this.tableData = newArray;
    if (this.$route.params.openType === "add") {
      this.formData.dmmc = this.$route.params.dmmc;
      this.formData.jcsj = moment(this.$route.params.jcsj).format('YYYY-MM-DD');
      this.formData.xzqhdm = this.$route.params.xzqhcode;
      this.formData.xzqhname = this.$route.params.xzqhname;
    } else if (this.$route.params.openType === "edit") {
      this.fetchDataById(this.$route.params.id);
    }
  },
  methods: {
    handxiazai(name) {
      let url = process.env.VUE_APP_URL_URL + name;
      window.open(url);
    },
    calculateCategories() {
      // 遍历表格数据
      this.tableData.forEach((item) => {
        this.calculateCategory(item);
      });
    },
    // 根据ID调用接口获取数据
    fetchDataById(id) {
      if (!id) {
        this.goBack();
        return;
      }
      this.$api
        .getNDmSzjcDataById(id)
        .then((response) => {
          console.log("根据id拿到的数据", response);
          // 根据接口返回的数据设置输入框的默认值
          this.formData = response.data.data; // 假设接口返回的数据直接包含表单数据，根据实际情况进行调整
          this.formData.xzqhname = this.$route.params.xzqhname;
          // 计算类别并赋值给每一行监测因子的对象
          this.calculateCategories();
          this.showUploadedFiles();
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
        });
    },
    submitForm(shzt) {
      if (this.fileList.length == 0) {
        this.$message.info("请上传监测报告！");
        return;
      }
      console.log('-----------', this.formData.jcsj);
      if (this.formData.jcsj === '') {
        this.$message.info("请填写监测日期！");
        return;
      }
      let str = '';
      if (this.formData.jianceshujulx == '01') {
        for (let i = 0; i < this.tableData.length; i++) {
          const element = this.tableData[i];
          console.log(this.formData[element.jcxm]);
          if (this.formData[element.jcxm] === '' || this.formData[element.jcxm] == null) {
            this.$message.info("水质监测值请填写完整！");
            return;
          }
        }
        // 将所有测定值进行比较
        // let maxCategory = this.tableData.reduce((prev, current) =>
        //   prev.lb > current.lb ? prev : current
        // ).lb;
        let maxCategory = this.tableData.reduce((prev, current) => {
          if (prev.jcxm == 'zd' || prev.jcxm == 'fdcjq') {
            return current;
          } else if (current.jcxm == 'zd' || current.jcxm == 'fdcjq') {
            return prev;
          }
          return prev.lb > current.lb ? prev : current
        }
        ).lb;
        console.log(maxCategory);
        this.formData.szlb = maxCategory;
        str = `当前水质类别为：${config.typeArray.find((item) => item.value == maxCategory).label}，是否确定？`;
      } else if (this.formData.jianceshujulx == '03' || this.formData.jianceshujulx == '05') {
        this.formData.szlb = 0;
        str = '当前断面为：断流，是否确定？';
      }
      this.$confirm(str, "确认提交",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 提交表单的逻辑
          console.log("提交的表单数据:", this.formData);
          // 用户点击了确定按钮，执行提交操作
          if (this.$route.params.openType === "add") {
            this.formData.shenhezt = shzt;
            this.addData(this.formData);
          } else if (this.$route.params.openType === "edit") {
            this.formData.shenhezt = shzt;
            this.xiugai(this.formData);
          }
        })
        .catch(() => {
          // 用户点击了取消按钮，不执行提交操作
        });
    },
    addData(data) {
      this.$api.addNDmSzjcData(data).then((response) => {
        if (response.data.code == 0) {
          this.$message.success(response.data.data);
          this.goBack();
        } else {
          this.$message("录入失败！");
        }
      });
    },
    xiugai(data) {
      this.$api.editNDmSzjcData(data).then((response) => {
        if (response.data.code == 0) {
          this.$message.success(response.data.data);
          this.goBack();
        } else {
          this.$message("修改失败！");
        }
      });
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code == 0) {
        if (fileList.every(item => item.status == 'success')) {
          fileList.map(item => {
            item.response && this.fileList.push({ name: item.response.data[0].newFileName, url: process.env.VUE_APP_URL_URL + item.response.data[0].newFileName })
          })
        }
        this.formData.filename = this.fileList
          .map((item) => {
            return item.name;
          })
          .join();
      }
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.formData.filename = fileList
        .map((item) => {
          return item.name;
        })
        .join();
    },
    handerror(err, file, fileList) {
      console.log(err, file, fileList);
    },
    showUploadedFiles() {
      console.log("进来了");
      // 如果 formData 中存在已上传的文件名
      console.log("22", this.formData.filename);
      if (this.formData.filename) {
        console.log("又进来了");
        // 拆分文件名字符串，使用逗号作为分隔符
        const filenames = this.formData.filename.split(",");
        console.log("filenames", filenames);
        // 遍历每个文件名，构建完整的文件地址，并将地址放入 fileList 中
        filenames.forEach((filename) => {
          if (filename.trim() !== "") {
            const fileUrl = process.env.VUE_APP_URL_URL + filename;
            console.log("文件地址", fileUrl);

            this.fileList.push({
              name: filename,
              url: fileUrl,
            });
          }
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    calculateCategory(row) {
      console.log('=========', row);
      const value = this.formData[row.jcxm];
      console.log(value, isNaN(value), Boolean(value));
      row.cdz = value;
      let isNumber = /^-?\d+(\.\d+)?$/.test(value);
      if (!isNumber || value === '' || value === null || row.jcxm == "sw" || row.jcxm == "ph") {
        row.lb = "";
        return;
      }

      // 用户输入的值
      const lb = [row.lb1, row.lb2, row.lb3, row.lb4, row.lb5]; // 获取当前监测因子对象的 lb1 到 lb5
      const fh = row.fh; // 获取比较符号
      for (let j = 0; j < lb.length; j++) {
        if (
          (fh === ">=" && value >= lb[j]) ||
          (fh === "<=" && value <= lb[j])
        ) {
          // 如果用户输入的值满足某个标准值，设置对应的水质类别并结束循环
          row.lb = j + 1;
          return;
        }
      }
      // 如果用户输入的值小于所有标准值，设置为劣Ⅴ类
      row.lb = 6;
    },
    splitTableData(code) {
      if (code == 1) {
        return this.tableData.filter((item, index) => index % 2 === 0);
      } else if (code == 2) {
        return this.tableData.filter((item, index) => index % 2 !== 0);
      }
    },
    goBack() {
      // this.$router.go(-1);
      this.$router.push({ name: 'DataEntry' })
    },
    // 模板上传
    handleChange(file, fileList) {
      console.log("文件", file.name, file);
      let isExcel = file.name.endsWith('.xls') || file.name.endsWith('.xlsx');
      if (!isExcel) {
        this.$message.error('仅支持上传 .xls 或 .xlsx 格式的文件！');
        return
      }
      let formobj = {
        sw: null,
        // swfl: null,
        ph: null,
        // phfl: null,
        rjy: null,
        gmsyzs: null,
        cod: null,
        bod5: null,
        nh3n: null,
        zl: null,
        zd: null,
        tong: null,
        xin: null,
        meng: null,
        fhw: null,
        xi: null,
        shen: null,
        gong: null,
        ge: null,
        luo: null,
        qian: null,
        qhw: null,
        hff: null,
        syl: null,
        ylzbmhxj: null,
        lhw: null,
        fdcjq: null,
        zl1: null,
      }
      const uploadedFile = file;
      const reader = new FileReader();
      reader.onload = (event) => {
        const content = event.target.result;
        const workbook = XLSX.read(content, { type: "binary" });
        // console.log("文件数据", workbook);
        // 获取 Excel 文件的第一个工作表
        const sheetName = workbook.SheetNames[0];
        // console.log("sheetName", sheetName);
        const sheet = workbook.Sheets[sheetName];
        // console.log("sheet", sheet);
        console.log('tableData', this.tableData);
        let range = XLSX.utils.decode_range(sheet['!ref']);
        if (Math.abs(range.e.c - range.s.c) > 10) {
          // 将工作表内容转换为 JSON 格式
          const jsonData = XLSX.utils.sheet_to_json(sheet);
          console.log('jsonData+++', jsonData);
          let obj = jsonData[0]
          // 遍历从Excel中读取的jsonData
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              const value = obj[key];
              // 检查是否在配置文件中找到对应的 label
              const matchedLabel = config.jcjgArray.find(
                (item) => item.label === key
              );
              if (matchedLabel) {
                const matchedValue = matchedLabel.value;
                // 将值赋给 formData 中 value 相同的字段
                formobj[matchedValue] = !isNaN(value) ? Math.abs(value) : '';
                // console.log(`Matched label: ${key}, Value: ${value}`);
              }
            }
          }
        } else {
          const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
          for (let i = 0; i < jsonData.length; i++) {
            const element = jsonData[i];
            const matchedLabel = config.jcjgArray.find(
              (item) => item.label === element[0]
            );
            if (matchedLabel) {
              const matchedValue = matchedLabel.value;
              // 将值赋给 formData 中 value 相同的字段
              formobj[matchedValue] = !isNaN(element[1]) ? Math.abs(element[1]) : '';
              // console.log(`Matched label: ${key}, Value: ${value}`);
            }
          }
        }
        this.formData = { ...this.formData, ...formobj };
        this.calculateCategories();
      };
      reader.readAsBinaryString(uploadedFile);
      // this.calculateCategories();
    },
    handdatepicker(date) {
      console.log(date);
      if (date == null) {
        this.formData.jcsj = moment(this.$route.params.jcsj).format('YYYY-MM-DD');
      }
    },
    pickerOptions() {
      let _this = this;
      return {
        disabledDate(time) {
          let startdate = moment(_this.formData.jcsj).startOf('month');
          let enddate = moment(_this.formData.jcsj).endOf('month');
          return !moment(time).isBetween(startdate, enddate, null, '[]');
        },
      }
    }
  },
};
</script>

<style>
.app-main {
  height: auto !important;
  /* 设置高度为自动以允许内容撑开 */
}

/* .box-padding {
  padding-bottom: 80px;
} */

.page-container {
  /* display: flex; */
}

.left-panel {
  flex: 1;
  padding: 20px;
  border-right: 1px solid #eee;
  overflow-y: auto;
  /* 左侧内容超出时显示滚动条 */
}

/* .right-panel {
  flex: 2;
  padding: 20px;

  overflow-y: auto;
} */
.right-panel {
  display: flex;
  padding: 20px;
  flex-direction: row;
}

.table-container {
  flex: 1;
  /* 自动填充剩余空间 */
  margin-right: 20px;
  /* 添加一些间距 */
}

.table-container:last-child {
  margin-right: 0;
  /* 最后一个表格容器不需要右边距 */
}

.table-container {
  overflow-y: auto;
  height: 100%;
}

.bottom-actions {
  /* position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%); */
  /* text-align: center; */
  /* margin-top: 20px; */
}

.bottom-actions {
  position: sticky;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  padding: 20px 0;
  background-color: #fff;
  /* 使按钮背景色为白色以覆盖可能存在的内容 */
  border-top: 1px solid #ececec;
}

.custom-suffix {
  line-height: 36px;
  /* 与 el-input 的高度相同 */
}

/* 隐藏输入框的上下箭头 */
input[type="number"] {
  -moz-appearance: textfield;
  /* Firefox */
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
  /* 可以根据需要调整 */
}
</style>
